package com.lishangshan.oas_system.controller.plan;

import com.github.pagehelper.util.StringUtil;
import com.lishangshan.oas_system.model.dao.notedao.AttachmentDao;
import com.lishangshan.oas_system.model.dao.plandao.PlanDao;
import com.lishangshan.oas_system.model.dao.plandao.Planservice;
import com.lishangshan.oas_system.model.dao.system.StatusDao;
import com.lishangshan.oas_system.model.dao.system.TypeDao;
import com.lishangshan.oas_system.model.dao.user.UserDao;
import com.lishangshan.oas_system.model.entity.note.Attachment;
import com.lishangshan.oas_system.model.entity.plan.Plan;
import com.lishangshan.oas_system.model.entity.system.SystemStatusList;
import com.lishangshan.oas_system.model.entity.system.SystemTypeList;
import com.lishangshan.oas_system.service.mail.MailServices;
import com.lishangshan.oas_system.utils.FileUpload;
import com.lishangshan.oas_system.utils.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/")
public class PlanListController {
    private int size = ParameterUtil.PAGE_SIZE_MIN;
    private Pageable pa = null;
    @Autowired
    private TypeDao typeDao;
    @Autowired
    private StatusDao statusDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private Planservice planservice;
    @Autowired
    private PlanDao planDao;
    @Autowired
    private FileUpload fileUpload;
    @Autowired
    private MailServices mailServices;

    /**
     * 页面初始化
     *
     * @param page
     * @param model
     * @param userId
     * @return
     */
    @RequestMapping("planview")
    public String indexPlan(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model
            , @SessionAttribute("userId") Long userId) {
        typeAndStatusInfo(model);
        pa = new PageRequest(page, size);
        Page<Plan> planPage = planDao.findByUserOrderByCreateTimeDesc(userId, pa);
        model.addAttribute("plist", planPage.getContent());
        model.addAttribute("page", planPage);
        model.addAttribute("url", "indexPlanpaging");
        return "plan/planview";
    }

    /**
     * 分页 排序
     *
     * @param page
     * @param model
     * @param userId
     * @param baseKey
     * @param type
     * @param status
     * @param time
     * @return
     */
    @RequestMapping("indexPlanpaging")
    public String indexPlanpaging(@RequestParam(value = "page", defaultValue = ParameterUtil.PAGE_NUMBER) int page, Model model,
                                  @SessionAttribute("userId") Long userId, @RequestParam(value = "baseKey", defaultValue = "") String baseKey,
                                  @RequestParam(value = "type", defaultValue = "") Object type,
                                  @RequestParam(value = "status", defaultValue = "") Object status,
                                  @RequestParam(value = "time", defaultValue = "") Object time
    ) {
        typeAndStatusInfo(model);
        Page<Plan> planPage = planservice.paging(page, size, baseKey, userId, type, status, time);
        model.addAttribute("plist", planPage.getContent());
        model.addAttribute("page", planPage);
        model.addAttribute("url", "indexPlanpaging");
        model.addAttribute("sort", "&baseKey=" + baseKey + "&type=" + type + "&status=" + status + "&timef=" + time);
        return "plan/planviewtable";
    }

    /**
     * 跳转 添加或修改
     *
     * @param pid
     * @param model
     * @return
     */
    @RequestMapping("planedit")
    public String planedit(@RequestParam("pid") Long pid, Model model, HttpServletRequest req) {
        Plan plans = null;
        if (pid == -1) {
            System.out.println("进入添加");
        } else {
            System.out.println("进入修改");
            plans = planDao.findOne(pid);
        }
        model.addAttribute("plan", plans);
        model.addAttribute("pid", pid);
        model.addAttribute("pageflag", req.getParameter("pageflag"));
        typeAndStatusInfo(model);
        return "plan/planedit";
    }

    @Autowired
    private AttachmentDao attachmentDao;

    /**
     * 修改 添加
     *
     * @param req
     * @param plan
     * @return
     */
    @RequestMapping("plansave")
    public String plansave(HttpServletRequest req, Plan plan, @RequestParam(value = "file", required = false) MultipartFile file, @SessionAttribute("userId") Long userId) {

        // 上传文件 and 修改文件 如果 file 不为空
//        if (!Objects.isNull(req.getParameter("file"))) {
        if (!StringUtil.isEmpty(file.getOriginalFilename())) {
            try {
                // 保存 附件
                Attachment attachment = mailServices.upload(file, userDao.findOne((Long) req.getSession().getAttribute("userId")));
                attachment.setModel("plan");
                Attachment save = attachmentDao.save(attachment);
                System.out.println("save");
                // 设置附件id
                plan.setAttachId(save.getAttachmentId());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 如果 为-1 则 是添加
        if ("-1".equals(req.getParameter("pid"))) {
            plan.setCreateTime(new Date());
            System.out.println("进入添加");
        } else {
            // 设置 时间
            Plan plan1 = planDao.findOne(Long.parseLong(req.getParameter("pid")));
            plan.setCreateTime(plan1.getCreateTime());
            // 如果修改时没有选择附件， 则表没有修改附件 用原来的附件
            if (StringUtil.isEmpty(file.getOriginalFilename())) {
                plan.setAttachId(plan1.getAttachId());
                plan.setCreateTime(plan1.getCreateTime());
            }
            System.out.println("进入修改");
            // 为修改的附上主键id

            plan.setPlanId(Long.parseLong(req.getParameter("pid")));
        }
        plan.setUser(userDao.findOne(userId));
        System.out.println("paln" + plan);
        planDao.save(plan);
        return "forward:/planview?page=" + req.getParameter("pageflag");
    }


    /**
     * 附件 下载
     *
     * @param paid
     * @param model
     * @param response
     * @return
     */
    @RequestMapping("downPlan")
    public void downPlanFile(@RequestParam("paid") Long paid, Model model, HttpServletResponse response) throws IOException {
        Attachment attachment = attachmentDao.findOne(paid);
        if (attachment.getAttachmentPath() == null) {
            model.addAttribute("errormess", "附件下载异常");
        } else {
            fileUpload.fileDownload(attachment.getAttachmentPath(), response);
            model.addAttribute("success", "开始下载");
        }
    }

    /**
     * 计划 删除
     * @param pid
     * @param model
     * @param req
     * @return
     */
    @RequestMapping("plandelete")
    public String plandelete(@RequestParam("pid") Long pid, Model model, HttpServletRequest req) {
        Plan planOne = planDao.findOne(pid);
        // 如果 该条计划有相对应附件 删除该附件
        if (planOne.getAttachId() != null) {
            attachmentDao.delete(planOne.getAttachId());
        } else {
            // 不做操作
        }
        // 附件删除后删除主表 数据
        planDao.delete(pid);
        model.addAttribute("success", "删除成功！");
        return "forward:/planview?page=" + req.getParameter("pageflag");
    }

    /**
     * 状态 和类型
     *
     * @param model
     */
    private void typeAndStatusInfo(Model model) {
        List<SystemTypeList> typeLists = typeDao.findByTypeModel("aoa_plan_list");
        List<SystemStatusList> statusLists = statusDao.findByStatusModel("aoa_plan_list");
        model.addAttribute("typelist", typeLists);
        model.addAttribute("statuslist", statusLists);
    }

}
